package com.gitee.ly.chain.utils;

import java.util.*;
import java.util.function.Function;

/**
 * StreamEx
 *
 * @author ly
 **/
public class StreamEx {
    public static <T, F> int distinctCount(List<T> list, Function<? super T, ? extends F>... fileds) {
        Set<String> set = new HashSet<>();
        if (list != null) {
            for (T item : list) {
                if (item != null) {
                    StringJoiner stringJoiner = new StringJoiner("@@##@@");
                    for (Function<? super T, ? extends F> filed : fileds) {
                        F obj = filed.apply(item);
                        if (obj != null) {
                            stringJoiner.add(obj.toString());
                        } else {
                            stringJoiner.add("null");
                        }
                    }
                    set.add(stringJoiner.toString());
                }
            }
        }
        return set.size();
    }

    public static <T> T findFirstOne(List<T> list, Function<? super T, ? extends Boolean> match) {
        if (list == null) {
            return null;
        }
        for (T t : list) {
            if (match.apply(t)) {
                return t;
            }
        }
        return null;
    }

    /**
     * 分组
     */
    public static <T, V> Map<V, T> groupBy(List<T> list, Function<? super T, ? extends V> groupMatch) {
        Map<V, T> map = new HashMap<>(8);
        if (list == null || list.size() == 0) {
            return map;
        }
        for (T item : list) {
            if (item != null) {
                V groupTag = groupMatch.apply(item);
                map.put(groupTag, item);
            }
        }
        return map;
    }
}
